<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            /*padding: 0;*/
        }

        #box {
            position: relative;
            width: 200px;
            height: 200px;
            background-color: yellowgreen;
        }

        #box1 {
            position: relative;
            width: 200px;
            height: 200px;
            background-color: darkmagenta;
        }
    </style>
</head>
<body>
<button id="btn400">去把皮卡丘400</button>
<button id="btn800">去把皮卡丘800</button>
<div id="box"></div>
<div id="box1"></div>
<script>
    var btn400 = document.getElementById("btn400");
    var btn800 = document.getElementById("btn800");
    var box = document.getElementById("box");
    var box1 = document.getElementById("box1");
    btn400.onclick = function () {
        animate(box, 400);
        animate(box1, 400);
    }
    btn800.onclick = function () {
        animate(box, 800)
        animate(box1, 800)
    }

    function animate(element, target) {
        //先清除定时器
        clearInterval(element.timerId);
        //开启定时器
        element.timerId = setInterval(function () {
            var current = element.offsetLeft;//获取当前位置
            var step = 10;//步长
            step = current < target ? step : -step;
            if (Math.abs(current - target) >= Math.abs(step)) {//如果当前位置小于目标位置 就继续走
                //盒子的距离 = 盒子当前的距离 + 步长
                element.style.left = current + step + "px";
            } else {
                element.style.left = target + "px";//手动放到目标位置
                clearInterval(element.timerId);//清除定时器
            }
        }, 15)
    }

</script>
</body>
</html>